1   /*
2    * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
3    *
4    * Redistribution and use in source and binary forms, with or without
5    * modification, are permitted provided that the following conditions
6    * are met:
7    *
8    *   - Redistributions of source code must retain the above copyright
9    *     notice, this list of conditions and the following disclaimer.
10   *
11   *   - Redistributions in binary form must reproduce the above copyright
12   *     notice, this list of conditions and the following disclaimer in the
13   *     documentation and/or other materials provided with the distribution.
14   *
15   *   - Neither the name of Oracle nor the names of its
16   *     contributors may be used to endorse or promote products derived
17   *     from this software without specific prior written permission.
18   *
19   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
20   * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
21   * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22   * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24   * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25   * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26   * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27   * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28   * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29   * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30   */
31  
32  
33  import java.awt.*;
34  
35  
36  /**
37   * A simple bar chart demo
38   * @author Sami Shaio
39   * @modified 06/21/00 Daniel Peek : refactored, comments
40   */
41  @SuppressWarnings("serial")
42  public class BarChart extends java.applet.Applet {
43  
44      private static final int VERTICAL = 0;
45      private static final int HORIZONTAL = 1;
46      private static final int SOLID = 0;
47      private static final int STRIPED = 1;
48      private int orientation;
49      private String title;
50      private Font font;
51      private FontMetrics metrics;
52      private int columns;
53      private int values[];
54      private Color colors[];
55      private String labels[];
56      private int styles[];
57      private int scale = 10;
58      private int maxLabelWidth = 0;
59      private int barSpacing = 10;
60      private int maxValue = 0;
61  
62      @Override
63      public void init() {
64  
65          getSettings();
66  
67          values = new int[columns];
68          labels = new String[columns];
69          styles = new int[columns];
70          colors = new Color[columns];
71  
72          for (int i = 0; i < columns; i++) {
73              parseValue(i);
74              parseLabel(i);
75              parseStyle(i);
76              parseColor(i);
77          }
78      }
79  
80      private void getSettings() {
81          font = new java.awt.Font("Monospaced", Font.BOLD, 12);
82          metrics = getFontMetrics(font);
83  
84          title = getParameter("title");
85          if (title == null) {
86              title = "Chart";
87          }
88  
89          String temp = getParameter("columns");
90          if (temp == null) {
91              columns = 5;
92          } else {
93              columns = Integer.parseInt(temp);
94          }
95  
96          temp = getParameter("scale");
97          if (temp == null) {
98              scale = 10;
99          } else {
100             scale = Integer.parseInt(temp);
101         }
102 
103         temp = getParameter("orientation");
104         if (temp == null) {
105             orientation = VERTICAL;
106         } else if (temp.equalsIgnoreCase("horizontal")) {
107             orientation = HORIZONTAL;
108         } else {
109             orientation = VERTICAL;
110         }
111     }
112 
113     private void parseValue(int i) {
114         String temp = getParameter("C" + (i + 1));
115         try {
116             values[i] = Integer.parseInt(temp);
117         } catch (NumberFormatException e) {
118             values[i] = 0;
119         } catch (NullPointerException e) {
120             values[i] = 0;
121         }
122         maxValue = Math.max(maxValue, values[i]);
123     }
124 
125     private void parseLabel(int i) {
126         String temp = getParameter("C" + (i + 1) + "_label");
127         if (temp == null) {
128             labels[i] = "";
129         } else {
130             labels[i] = temp;
131         }
132         maxLabelWidth = Math.max(metrics.stringWidth(labels[i]), maxLabelWidth);
133     }
134 
135     private void parseStyle(int i) {
136         String temp = getParameter("C" + (i + 1) + "_style");
137         if (temp == null || temp.equalsIgnoreCase("solid")) {
138             styles[i] = SOLID;
139         } else if (temp.equalsIgnoreCase("striped")) {
140             styles[i] = STRIPED;
141         } else {
142             styles[i] = SOLID;
143         }
144     }
145 
146     private void parseColor(int i) {
147         String temp = getParameter("C" + (i + 1) + "_color");
148         if (temp != null) {
149             temp = temp.toLowerCase();
150             if (temp.equals("red")) {
151                 colors[i] = Color.red;
152             } else if (temp.equals("green")) {
153                 colors[i] = Color.green;
154             } else if (temp.equals("blue")) {
155                 colors[i] = Color.blue;
156             } else if (temp.equals("pink")) {
157                 colors[i] = Color.pink;
158             } else if (temp.equals("orange")) {
159                 colors[i] = Color.orange;
160             } else if (temp.equals("magenta")) {
161                 colors[i] = Color.magenta;
162             } else if (temp.equals("cyan")) {
163                 colors[i] = Color.cyan;
164             } else if (temp.equals("white")) {
165                 colors[i] = Color.white;
166             } else if (temp.equals("yellow")) {
167                 colors[i] = Color.yellow;
168             } else if (temp.equals("gray")) {
169                 colors[i] = Color.gray;
170             } else if (temp.equals("darkgray")) {
171                 colors[i] = Color.darkGray;
172             } else {
173                 colors[i] = Color.gray;
174             }
175         } else {
176             colors[i] = Color.gray;
177         }
178     }
179 
180     @Override
181     public void paint(Graphics g) {
182         // draw the title centered at the bottom of the bar graph
183         g.setColor(Color.black);
184         g.setFont(font);
185 
186         g.drawRect(0, 0, getSize().width - 1, getSize().height - 1);
187 
188         int titleWidth = metrics.stringWidth(title);
189         int cx = Math.max((getSize().width - titleWidth) / 2, 0);
190         int cy = getSize().height - metrics.getDescent();
191         g.drawString(title, cx, cy);
192 
193         // draw the bars and their titles
194         if (orientation == HORIZONTAL) {
195             paintHorizontal(g);
196         } else {  // VERTICAL
197             paintVertical(g);
198         }
199     }
200 
201     private void paintHorizontal(Graphics g) {
202         // x and y coordinates to draw/write to
203         int cx, cy;
204         int barHeight = metrics.getHeight();
205 
206         for (int i = 0; i < columns; i++) {
207 
208             // set the X coordinate for this bar and label and center it
209             int widthOfItems = maxLabelWidth + 3 + (maxValue * scale) + 5
210                     + metrics.stringWidth(Integer.toString(maxValue));
211             cx = Math.max((getSize().width - widthOfItems) / 2, 0);
212 
213             // set the Y coordinate for this bar and label
214             cy = getSize().height - metrics.getDescent() - metrics.getHeight()
215                     - barSpacing
216                     - ((columns - i - 1) * (barSpacing + barHeight));
217 
218             // draw the label
219             g.setColor(Color.black);
220             g.drawString(labels[i], cx, cy);
221             cx += maxLabelWidth + 3;
222 
223 
224             // draw the shadow
225             g.fillRect(cx + 4, cy - barHeight + 4,
226                     (values[i] * scale), barHeight);
227 
228             // draw the bar
229             g.setColor(colors[i]);
230             if (styles[i] == STRIPED) {
231                 for (int k = 0; k <= values[i] * scale; k += 2) {
232                     g.drawLine(cx + k, cy - barHeight, cx + k, cy);
233                 }
234             } else {      // SOLID
235                 g.fillRect(cx, cy - barHeight,
236                         (values[i] * scale) + 1, barHeight + 1);
237             }
238             cx += (values[i] * scale) + 4;
239 
240             // draw the value at the end of the bar
241             g.setColor(g.getColor().darker());
242             g.drawString(Integer.toString(values[i]), cx, cy);
243         }
244     }
245 
246     private void paintVertical(Graphics g) {
247         int barWidth = maxLabelWidth;
248 
249         for (int i = 0; i < columns; i++) {
250 
251             // X coordinate for this label and bar (centered)
252             int widthOfItems = (barWidth + barSpacing) * columns - barSpacing;
253             int cx = Math.max((getSize().width - widthOfItems) / 2, 0);
254             cx += (maxLabelWidth + barSpacing) * i;
255 
256             // Y coordinate for this label and bar
257             int cy = getSize().height - metrics.getHeight()
258                     - metrics.getDescent() - 4;
259 
260             // draw the label
261             g.setColor(Color.black);
262             g.drawString(labels[i], cx, cy);
263             cy -= metrics.getHeight() - 3;
264 
265             // draw the shadow
266             g.fillRect(cx + 4, cy - (values[i] * scale) - 4,
267                     barWidth, (values[i] * scale));
268 
269             // draw the bar
270             g.setColor(colors[i]);
271             if (styles[i] == STRIPED) {
272                 for (int k = 0; k <= values[i] * scale; k += 2) {
273                     g.drawLine(cx, cy - k,
274                             cx + barWidth, cy - k);
275                 }
276             } else {
277                 g.fillRect(cx, cy - (values[i] * scale),
278                         barWidth + 1, (values[i] * scale) + 1);
279             }
280             cy -= (values[i] * scale) + 5;
281 
282             // draw the value on top of the bar
283             g.setColor(g.getColor().darker());
284             g.drawString(Integer.toString(values[i]), cx, cy);
285         }
286     }
287 
288     @Override
289     public String getAppletInfo() {
290         return "Title: Bar Chart \n"
291                 + "Author: Sami Shaio \n"
292                 + "A simple bar chart demo.";
293     }
294 
295     @Override
296     public String[][] getParameterInfo() {
297         String[][] info = {
298             { "title", "string", "The title of bar graph.  Default is 'Chart'" },
299             { "scale", "int", "The scale of the bar graph.  Default is 10." },
300             { "columns", "int", "The number of columns/rows.  Default is 5." },
301             { "orientation", "{VERTICAL, HORIZONTAL}",
302                 "The orienation of the bar graph.  Default is VERTICAL." },
303             { "c#", "int", "Subsitute a number for #.  "
304                 + "The value/size of bar #.  Default is 0." },
305             { "c#_label", "string", "The label for bar #.  "
306                 + "Default is an empty label." },
307             { "c#_style", "{SOLID, STRIPED}", "The style of bar #.  "
308                 + "Default is SOLID." },
309             { "c#_color", "{RED, GREEN, BLUE, PINK, ORANGE, MAGENTA, CYAN, "
310                 + "WHITE, YELLOW, GRAY, DARKGRAY}",
311                 "The color of bar #.  Default is GRAY." }
312         };
313         return info;
314     }
315 }